package com.xuan.config;

import com.xuan.pojo.User;
import com.xuan.service.Impl.UserSerciceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

//自定义的realm
public class UserRealm extends AuthorizingRealm {
    @Autowired
    UserSerciceImpl userSercice;
//    授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权");
        //添加访问的认证标识
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission("user:add");//添加授权
        info.addStringPermission("user:update");

        //拿到当前登录的对象
//        Subject subject = SecurityUtils.getSubject();
//        User currentUser = (User) subject.getPrincipal();//拿到user对象
        return info;
//        return null;
    }
//
//      认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("执行了认证");
//     伪造数据库数据
      /*  String username="root";
        String password="123456";*/
//        从数据库中查用户

        UsernamePasswordToken userToken = (UsernamePasswordToken)token;
        User user = userSercice.queryUserByName(userToken.getUsername());

        System.out.println(user);
//        if (!userToken.getUsername().equals(username)){

//            if (!userToken.getUsername().equals(user.getName())){
        if(user==null){
             return null;//抛出异常 UnknownAccountException
        }

        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",user);

        return new SimpleAuthenticationInfo("",user.getPassword(),"");
//        return new SimpleAuthenticationInfo("",password,"");


    }
}
